package gatperdut.chato.core.interpreter.actions;

import gatperdut.chato.constants.CSConstantsCommandResult.CommandExecutionResult;
import gatperdut.chato.core.characters.BaseController;
import gatperdut.chato.core.interpreter.actions.generic.Action;
import gatperdut.chato.core.interpreter.grammar.comminfo.StopInfo;

public class StopAction extends Action {

    public StopAction( StopInfo info, BaseController entityController ) {
        super( info, entityController );
    }

    @Override
    public CommandExecutionResult perform() {
        boolean wasCrafting = getEntityController().getCraftThread() != null;

        checkForRunningCraft();

        if ( wasCrafting ) {
            return CommandExecutionResult.OK;
        }

        if ( getEntityController().getCombatController().isInCombat() ) {
            if ( !getEntityController().getCombatController().isAttacking() ) {
                getEntityController().tx( "You are not fighting back." );
                return CommandExecutionResult.OK;
            }
            else {
                getEntityController().getEchoes().txStopFighting();
                BaseController exTarget = getEntityController().getCombatController().getTarget();
                exTarget.getCombatController().removeAttacker( getEntityController() );
                getEntityController().getCombatController().setTarget( null );
                // --if command-issuer is not being attacked by anyone else,
                // combat is over.
                if ( getEntityController().getCombatController().combatCanEnd() ) {
                    getEntityController().getCombatController().stopCombatThread();
                }
                // --if the ex-target is not fighting back and noone else is
                // attacking her, combat is over.
                if ( exTarget.getCombatController().combatCanEnd() ) {
                    exTarget.getCombatController().stopCombatThread();
                }
                return CommandExecutionResult.OK;
            }
        }
        else {
            getEntityController().tx( "You are neither crafting nor fighting." );
            return CommandExecutionResult.OK;
        }
    }

    @Override
    public boolean interruptsCrafting() {
        return true;
    }

    @Override
    public StopInfo getInfo() {
        return (StopInfo) super.getInfo();
    }

}
